package com.skstudio.nuprint.lpd;

import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;

public class CommandHandler {
	Reader mReader = null;
	Writer mWriter = null;
	
	public CommandHandler(Reader in, Writer out) {
		mReader = in;
		mWriter = out;
	}
	
	public void execute(byte[] command) throws Exception {		
	}
	
	public void acknowledge(int status) throws IOException {
		mWriter.write(status);
		mWriter.flush();
	}
	
	public static String createFixedLengthString(String s, int length)
	{
		String result = null;
		if (s.isEmpty())
		{
			StringBuilder sb = new StringBuilder(length);
			for (int i = 0; i < length; i++)
			{
				sb.append(" ");
			}
			result = sb.toString();
		}
		else
		{
			if (s.length() == length)
			{
				result = s;
			}
			else if (s.length() > length)
			{
				result = s.substring(0, length);
			}
			else
			{
				// s.length() is < length
				StringBuilder sb = new StringBuilder(length);
				sb.append(s);
				for (int i = s.length(); i < length; i++)
				{
					sb.append(" ");
				}
				result = sb.toString();
			}
		}
		return result;
	}
	
	public static String[] parseOperands(byte[] command) {
		ArrayList<String> opds = new ArrayList<String> ();
		StringBuilder sb = new StringBuilder();
		
		for(int i = 1; i < command.length; i++) {
			char c = (char) command[i];
			
			if (Character.isWhitespace(c) || c == '\012') {
				String opd = sb.toString();
				opds.add(opd);
				
				sb = new StringBuilder();
			} else {
				sb.append(c);
			}
		}
		String[] list = new String[opds.size()];
		return opds.toArray(list);
	}
	
	public static String[] parseOperands(String command) {
		ArrayList<String> opds = new ArrayList<String> ();
		StringBuilder sb = new StringBuilder();
		
		for(int i = 1; i < command.length(); i++) {
			char c = command.charAt(i);
			
			if (Character.isWhitespace(c) || c == '\012' || (i + 1 == command.length())) {
				String opd = sb.toString();
				opds.add(opd);
				
				sb = new StringBuilder();
			} else {
				sb.append(c);
			}
		}
		String[] list = new String[opds.size()];
		return opds.toArray(list);
	}
}
